import React, { useEffect, useMemo, useRef, useState } from "react";
import style from "./style.module.scss";
import { WdChatItem } from "../../../components/wd-chat-item";
import { useRequest, useSetState } from "ahooks";
import "../../../assets/font/iconfont.css";
import {
  FormParamState,
  getChatListHistory,
  putSendMessage,
  queryUserRecord,
} from "../../../api/askApi";
import { WDHeader } from "../../../components";
import { Input, Button, Popup, Flex } from "react-vant";
import OSS from "ali-oss";
import { addEmoji, emojiList, emojiReplaceString } from "../../../utils/emoji";

addEmoji("👁", "[ABC]");
const ws = new WebSocket('ws://localhost:8080')
const store = new OSS({
  region: "oss-cn-shanghai",
  accessKeyId: "LTAI5tCBCXoEXSGqWVMSPy6e",
  accessKeySecret: "snwNUOxazBV0SIYkQn95fBhzd7fCax",
  bucket: "2109a-wd",
});

// 当前聊天的医生类型
interface CurrentDoctorState {
  department: string;
  departmentId: number;
  doctorId: number;
  doctorName: string;
  evaluateStatus: number;
  vedioPic: string;
  inquiryTime: number;
  jiGuangPwd: string;
  jobTitle: string;
  recordId: number;
  userName: string;
}

// 聊天项目类型
export interface ChatItemState {
  askTime: number;
  content: string;
  direction: 1 | 2;
  doctorHeadPic: string;
  msgType: 1;
  userHeadPic: string;
}

const Index: React.FC = () => {
  // 获取滑动的节点
  const sectionEl = useRef<HTMLElement | null>(null);
  // 获取当前医生信息
  const { data: currentDoctor = {} as CurrentDoctorState } = useRequest(
    async () => {
      const resp = await queryUserRecord();
      console.log("当前医生数据", resp.result);
      run(resp.result.recordId);
      setParams({
        doctorId: resp.result.doctorId,
        inquiryId: resp.result.recordId,
      });
      return resp.result as CurrentDoctorState;
    }
  );
  // 获取 源数据 聊天列表
  const { data: chatListHistory = [], run } = useRequest(
    async (id: number) => {
      const params = {
        count: 50,
        page: 1,
        inquiryId: id,
      };
      const resp = await getChatListHistory(params);
      return resp.result as ChatItemState[];
    },
    { manual: true }
  );

  // 处理原始数据  倒序
  const rendeRchatListHistory = useMemo(() => {
    const data = [...chatListHistory].reverse();
    // console.log("聊天列表", data);
    return data;
  }, [chatListHistory]);

  // 请求发送的参数
  const [params, setParams] = useSetState<FormParamState>({
    content: "",
    type: 1,
  } as FormParamState);

  // 发送函数
  const sendMessage = async (type: string, con?: string) => {
    let content = "";
    if (type === "text") {
      // 处理文本
      content = JSON.stringify({
        type: type,
        con: emojiReplaceString(params.content),
      });
    } else {
      // 处理媒体
      content = JSON.stringify({
        type: type,
        con: con,
      });
    }

    const { status } = await putSendMessage({ ...params, content });
    if (status === "0000") {
      // 重新请求聊天列表
      run(params.inquiryId);
      // 清空input内容
      setParams({ content: "" });
      // 通知webscoket服务器
      ws.send("消息来了")
    }
  };
  const [visible, setVisible] = useState(false);
  const [isShowEmojiList, setIsShowEmojiList] = useState(false);
  // 展示弹出层
  const showDialog = () => {
    setVisible(true);
  };
  const handleUpload = (type: "image" | "video") => {
    // 处理上传逻辑
    // 1. 关闭弹出层
    setVisible(false);
    // 2. 弹出文件选择器
    const input = document.createElement("input");
    input.type = "file";
    // 开启多选
    input.multiple = true;
    input.click();
    // 3. 监听选中的文件
    input.addEventListener("change", () => {
      // 3-1. 判断 获取选中选中的文件
      if (input.files) {
        // 3-2 获取参数列表
        const files = [...input.files];
        // 3-3 循环文件列表
        files.forEach((file) => {
          // 3-4 将每一个文件上传  => oss 阿里云
          store.put(file.name, file).then((result) => {
            sendMessage(type, result.url);
          });
        });
      }
    });
  };

  const handleSelectEmoji = (emoji: string) => {
    setParams({
      content: params.content + emoji,
    });
    setVisible(false);
  };

  useEffect(() => {
    // 滑动到底部
    if (sectionEl.current) {
      sectionEl.current.scrollTop = 1000000;
    }
  }, [rendeRchatListHistory]);
  const min5 = 5 * 60 * 1000;


  useEffect(() => {


    ws.onopen = () => {
      console.log('患者端和服务器建立了WebSocket链接')
    }

    ws.onmessage = () => {
      console.log('患者端服务器消息来了')
      run(params.inquiryId);
    }
  }, [params.inquiryId])

  // useEffect(() => {
  //   let timer;
  //   if (params.inquiryId) {
  //     console.log('定时器开始')
  //     timer = setInterval(() => {
  //       run(params.inquiryId);
  //     }, 1000);
  //   }

  //   return () => {
  //     clearInterval(timer);
  //   };
  // }, [params.inquiryId]);

  return (
    <div className={style.chat}>
      <header className={style.header}>
        <WDHeader
          showSearch={false}
          title={currentDoctor.doctorName}
        ></WDHeader>
      </header>
      <section className={style.section} ref={sectionEl}>
        <div className={style.chatList}>
          {rendeRchatListHistory.map((v, i) => {
            const prev = rendeRchatListHistory[i - 1];

            return (
              <WdChatItem
                key={i}
                v={v}
                showTime={
                  i === 0
                    ? true
                    : v.askTime - prev.askTime > min5
                    ? true
                    : false
                }
              ></WdChatItem>
            );
          })}
        </div>
      </section>
      <footer className={style.footer}>
        <Input
          className={style.input}
          onKeyDown={(e) => e.keyCode === 13 && sendMessage("text")}
          // 受控组件
          value={params.content}
          onChange={(value) => setParams({ content: value })}
        ></Input>
        <Button
          type="primary"
          className={style.btn}
          onClick={() => sendMessage("text")}
        >
          发送
        </Button>
        <Button type="info" className={style.btn} onClick={() => showDialog()}>
          +
        </Button>
      </footer>
      <Popup
        visible={visible}
        position="bottom"
        onClose={() => setVisible(false)}
      >
        {isShowEmojiList ? (
          <div style={{ padding: "2px", minHeight: 200 }}>
            <Flex align="center" wrap="wrap">
              {emojiList.map((v, i) => {
                return (
                  <Flex.Item
                    span={6}
                    key={i}
                    style={{ textAlign: "center" }}
                    onClick={() => handleSelectEmoji(v.emoji)}
                  >
                    <span style={{ fontSize: 50 }}>{v.emoji}</span>
                  </Flex.Item>
                );
              })}
            </Flex>
          </div>
        ) : (
          <div style={{ padding: "2px", minHeight: 200 }}>
            <Flex justify="center" align="center" wrap="wrap">
              <Flex.Item span={6} onClick={() => setIsShowEmojiList(true)}>
                <i className="iconfont icon-biaoqing"></i>
              </Flex.Item>
              <Flex.Item span={6} onClick={() => handleUpload("image")}>
                <i className="iconfont icon-Image" style={{ fontSize: 30 }}></i>
              </Flex.Item>
              <Flex.Item span={6} onClick={() => handleUpload("video")}>
                <i className="iconfont icon-shipin_o"></i>
              </Flex.Item>
            </Flex>
          </div>
        )}
      </Popup>
    </div>
  );
};

export default Index;
